﻿using Admin.Application.Jobs;
using Admin.Authorization;
using Framework.Core;
using Framework.Core.Attributes;
using Framework.Core.Cache;
using Framework.Core.JsonSerialization.Extensions;
using Framework.Core.JsonSerialization.Providers;
using Framework.Core.ObjectMapper.Mapster;
using Framework.Core.Startup;
using Framework.DI;
using Framework.ExtensionsMods.Quartz;
using Framework.ExtensionsMods.Quartz.Model;
using Framework.ExtensionsMods.Quartz.Server;
using Framework.ExtensionsMods.Quartz.Server.IServer;
using Framework.SqlSugar;
using Framework.WebApi;
using Framework.WebApi.Authentication;
using Framework.WebApi.CorsAccessor;
using Framework.WebApi.IPRate;
using Framework.WebApi.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Savorboard.CAP.InMemoryMessageQueue;
using static NewLife.Remoting.ApiHttpClient;

namespace Admin
{
	[DependsOn<WebApiStartup>]
	public class RunAppStartup : StartupModule<RunAppStartup>
	{
		/// <summary>
		/// 程序启动器
		/// </summary>
		public RunAppStartup() => Order = 0;

		public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
		{
			// 缓存注册（新生命Redis组件） 
			webApplicationBuilder.Services.AddCache();

			webApplicationBuilder.Services.AddSqlSugar();                       // 添加 SqlSugar配置

			webApplicationBuilder.Services.AddOptions<JWTSettingsOptions>().Bind(webApplicationBuilder.Configuration.GetSection("JwtSettings"), options =>
			{
				options.BindNonPublicProperties = true; // 绑定私有变量
			}).ValidateDataAnnotations();

			//webApplicationBuilder.Services.AddSingleton(new AppSettings(webApplicationBuilder.Configuration));

			// Json序列化设置
			static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
			{
				//修改属性名称的序列化方式，首字母小写，即驼峰样式
				setting.ContractResolver = new CamelCasePropertyNamesContractResolver();

				// DateOnly 和 TimeOnly 类型序列化支持
				setting.Converters.AddDateOnlyConverters();
				setting.Converters.AddTimeOnlyConverters();

				//日期类型默认格式化处理 方式1
				setting.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy/MM/dd HH:mm:ss" });
				////日期类型默认格式化处理 方式2
				//setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
				//setting.DateFormatString = "yyyy/MM/dd HH:mm:ss";

				//忽略循环引用
				setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

				//序列化属性名大写（属性原样输出），解决命名不一致问题 
				setting.ContractResolver = new DefaultContractResolver();

				//空值处理
				setting.NullValueHandling = NullValueHandling.Ignore;
			};

			// 添加 Newtonsoft.Json 扩展配置(设置序列化提供器)
			webApplicationBuilder.Services.AddControllers()
				.AddNewtonsoftJsonExtensions<NewtonsoftJsonSerializerProvider>(webApplicationBuilder.Services,
				options => SetNewtonsoftJsonSetting(options.SerializerSettings));

			//// 添加 Newtonsoft.Json 扩展配置(不设置序列化提供器)
			//webApplicationBuilder.Services.AddControllers()
			//	.AddNewtonsoftJsonExtensions(webApplicationBuilder.Services,
			//	options => SetNewtonsoftJsonSetting(options.SerializerSettings));

			//// 添加 Newtonsoft.Json 扩展（不修改默认配置）
			//webApplicationBuilder.Services.AddControllers().AddNewtonsoftJsonExtensions(webApplicationBuilder.Services);

			webApplicationBuilder.Services.AddDependencyInjection();            // 添加依赖注入配置

			webApplicationBuilder.Services.AddMapster();                        // 添加 Mapster配置

			webApplicationBuilder.Services.AddAuthenticationJwtBearer();        // 添加 Jwt认证 配置
			webApplicationBuilder.Services.AddAppAuthorization<JwtHandler>();   // 添加 策略授权服务

			webApplicationBuilder.Services.AddIPRate();							// 添加IP访问限制服务

			webApplicationBuilder.Services.AddCorsAccessor();					// 添加跨域访问服务

			webApplicationBuilder.Services.AddCap(options =>			// 添加 CAP服务
			{
				options.UseInMemoryStorage();
				options.UseInMemoryMessageQueue();
			});

			//webApplicationBuilder.Services.AddSingleton<Job_SyncTest>();
			webApplicationBuilder.Services.AddJobTasks();
			webApplicationBuilder.Services.AddCaptcha();                        // 添加 验证码

			
		}

		public override void Configure(WebApplication webApplication)
		{
			webApplication.UseHttpsRedirection();

			webApplication.UseIPRate();

			webApplication.UseCorsAccessor();

			webApplication.UseAuthentication();
			webApplication.UseAuthorization();

			// 开启访问静态文件/wwwroot目录文件，要放在UseRouting前面
			webApplication.UseStaticFiles();

			ITaskSchedulerServer _schedulerServer = App.GetRequiredService<ITaskSchedulerServer>();
			SysTasks tasksQz = new SysTasks();
			tasksQz.ID = "1649960254726868992";
			tasksQz.Name = "Job_SyncTest";
			tasksQz.AssemblyName = "Admin.Application";
			tasksQz.ClassName = "Jobs.Job_SyncTest";
			tasksQz.RunTimes = 7;
			tasksQz.JobGroup = "SYSTEM";
			tasksQz.TriggerType = 0;
			tasksQz.IntervalSecond = 10;
			tasksQz.IsStart = true;
			tasksQz.TaskType = 1;
			tasksQz.BeginTime = DateTime.Now;
			tasksQz.EndTime = DateTime.Now.AddDays(1);
			var result = _schedulerServer.AddTaskScheduleAsync(tasksQz);
			if (result.Result.code == 200)
			{
				Console.WriteLine($"注册任务[{tasksQz.Name}]ID：{tasksQz.ID}成功");
			}

			// 开启响应缓存中间件
			// 使用CORS中间件时，必须在UseResponseCaching之前调用UseCors。
			webApplication.UseResponseCaching();

			webApplication.MapControllers();
		}
	}
}
